/**
 * 
 */
package com.soccer.cms.common.utils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zouqone
 * @date 2015年3月27日 上午12:29:48
 */
public class DBSquence {

    private static final long ONE_STEP = 10;
    private static final Lock LOCK = new ReentrantLock();
    private static long lastTime = System.currentTimeMillis();
    private static short lastCount = 0;
    private static int count = 0;

    public static String nextId() 
    {
    	return getUnique((int) ONE_STEP);
    }
    
    @SuppressWarnings("finally")
	public static String getUnique(Integer num){
    	String unique = null;
    	if(num == null){
    		num = (int) ONE_STEP;
    	}
        LOCK.lock();
        try {
            if (lastCount == num) {
                boolean done = false;
                while (!done) {
                    long now = System.currentTimeMillis();
                    if (now == lastTime) {
                        try {
                            Thread.currentThread();
                            Thread.sleep(1);
                        } catch (java.lang.InterruptedException e) {
                        }
                        continue;
                    } else {
                        lastTime = now;
                        lastCount = 0;
                        done = true;
                    }
                }
            }
            count = lastCount++;
        }
        finally 
        {
            LOCK.unlock();
            unique = lastTime+""+String.format("%03d",count); 
            return unique;
        }
        
    }
    
    public static String getIdByLength(Integer len){
    	String id = null;
    	 LOCK.lock();
         try {
             if (lastCount == len) {
                 boolean done = false;
                 while (!done) {
                     long now = System.currentTimeMillis();
                     if (now == lastTime) {
                         try {
                             Thread.currentThread();
                             Thread.sleep(1);
                         } catch (java.lang.InterruptedException e) {
                         }
                         continue;
                     } else {
                         lastTime = now;
                         lastCount = 0;
                         done = true;
                     }
                 }
             }
             count = lastCount++;
         }
         finally 
         {
             LOCK.unlock();
             id = ""+String.format("%0"+len+"d",count); 
             return id;
         }
    }
    
}
